<?php 
namespace Admin\Model;
use Think\Model;
class ShareModel extends Model{

	protected $_validate = array(
		array('shareName','require','分享名字不能为空'), //默认情况下用正则进行验证
		array('shareIntroduce','require','分享简介不能为空'), //默认情况下用正则进行验证
	);
	
	//获取数据
	public function getAll($id=null){
		//为空获取所以数据
		if(is_null($id)){
			$data = $this->select();
			return $data;
		}
		//获取1条数据
		else{
			$data = $this->find($id);
			return $data;
		}
		
	}
	
	//获取关联数据
	public function getJoin($id=null){
		if(is_null($id)){
			$data = $this->
			field('m_music.*,m_sorts.sortsname,m_author.authorname,m_author.authorImg,m_share.shareName')->
			join('left join m_sorts on m_music.sortsid = m_sorts.id')->
			join('left join m_author on m_music.authorId = m_author.id')->
			join('left join m_share on m_music.shareId = m_share.id')->
			select();
			return $data;
		}else{
			$data = $this->
			field('m_share.*,m_music.id,m_music.musicName,m_music.authorId,m_author.authorName')->
			join('left join m_music on m_music.shareId = m_share.id')->
			join('left join m_author on m_music.authorId = m_author.id')->
			where('m_share.id ='.$id)->
			select();
			return $data;
		}
		
	}
 
	//添加数据
	public function m_add(){
		if($this->create()){	
			//查询是否已有文章 
			$data = $this->where("shareName='{$_POST[shareName]}'")->find();
			if($data){
				$this->error = '添加失败，已有数据id为'.$data['id'];
				return false;
			}
 
			$path = $this->upload('sharePic','sharePic','文章封面上传失败');
			//组装
			$_POST['sharePic'] = $path[0];
			
			return $this->add($_POST);
		} 
	}
	
	//修改数据
	public function edit($id=null){
		if(is_null($id)){
			if($this->create()){
				return $this->save();
			} 
		}else{
			$data = $_POST;
		 
			$fine = $this->where("id={$id}")->save($data);
			return $fine;
		}
		
	}
	
	//删除数据
	public function del(){
		if($this->where('id='.I('get.id'))->delete()){
			return true;
		}
	}
	
	//删除文件
	public function unnk($data){
		unlink($data);
	}
	
	//封装上传类
	public function upload($name1=null,$name2=null,$txt=null){
		$upload = new \Think\Upload();// 实例化上传类
		// 上传文件 
		$info   =   $upload->upload(array($name1=>$_FILES[$name2]));
		if(!$info) {// 上传错误提示错误信息
			return	$this->error = $txt.$upload->getError();
		}else{// 上传成功
			foreach($info as $file){
				$data[]=$upload->rootPath.$file['savepath'].$file['savename'];
			}
			return $data;
		}
	}
}